package com.zhihaoliang.moshi.biz.decode

import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter

import com.squareup.moshi.Moshi
import com.zhihaoliang.moshi.util.log
import okio.ByteString
import okio.ByteString.Companion.decodeBase64


/**
 * @author 支豪亮
 * @date 2023/1/28 15:13
 * @des  Base64 的数据转化
 */

fun base64Decode(){
    val json = "\"TW9zaGksIE9saXZlLCBXaGl0ZSBDaGluPw\""

    val moshi = Moshi.Builder().add(ByteString::class.java, Base64ByteStringAdapter()).build()
    val jsonAdapter: JsonAdapter<ByteString> = moshi.adapter(ByteString::class.java)

    val byteString: ByteString? = jsonAdapter.fromJson(json)
    log(byteString.toString()) //输出 [text=Moshi, Olive, White Chin?]
}

class Base64ByteStringAdapter : JsonAdapter<ByteString>() {
    override fun fromJson(reader: JsonReader): ByteString? {
        val base64: String = reader.nextString()
        println(base64)
        return base64.decodeBase64()
    }

    override fun toJson(writer: JsonWriter, value: ByteString?) {
        val string = value?.base64()
        writer.value(string)
    }
}